//
//  CampusListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/23.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "CampusListViewController.h"
#import "CampusDetailViewController.h"
#import "CampusListSearchViewController.h"
#import "HomePageItemModel.h"
#import "CampusListItemCell.h"
#import "CampusListTypeHeaderView.h"
#import "LMJDropdownMenu.h"
#import "CampusParamItemModel.h"
#import "CampusListHeaderModel.h"
#import "CampusSchoolItemModel.h"
#import "CampusConfigModel.h"
@interface CampusListViewController ()<UITableViewDelegate,UITableViewDataSource,LMJDropdownMenuDataSource,LMJDropdownMenuDelegate,CampusListItemCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)CampusListTypeHeaderView *headerView;
@property (nonatomic,strong)LMJDropdownMenu *menuView;

@property (nonatomic,assign)NSInteger menuIndex;
@property (nonatomic,strong)CampusListHeaderModel *headerModel;
@property (nonatomic,strong)UILabel *noDataLb;

@property (nonatomic,assign)NSInteger pageIndex;

@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,copy)NSDictionary *cityDict;



@property (nonatomic,copy)NSArray *titleArray;

@property (nonatomic,strong,nullable)NSNumber *batchId;
@property (nonatomic,strong,nullable)NSNumber *provinceId;
@property (nonatomic,strong,nullable)NSNumber *hierarchyId;
@property (nonatomic,strong,nullable)NSNumber *typeId;

@property (nonatomic,strong)NSURLSessionTask *task;

@end

@implementation CampusListViewController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
    

    self.menuIndex = -1;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.menuView dismissMenu];
}

- (CampusListHeaderModel *)headerModel{
    if (!_headerModel) {
        _headerModel = [[CampusListHeaderModel alloc]init];
    }
    return _headerModel;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (NSDictionary *)cityDict{
    if (!_cityDict) {
        NSString *mainBundleDirectory = [[NSBundle mainBundle] bundlePath];
        NSString *path = [mainBundleDirectory stringByAppendingPathComponent:@"city.json"];
        NSURL *url = [NSURL fileURLWithPath:path];
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        _cityDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    }
    return _cityDict;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    [self showDataLoadState];
    [self loadDataSource];

}


- (void)setUI{
    
    self.menuIndex = -1;
    
    self.titleArray = @[@"province",@"type",@"hierarchy",@"batch"];
    
    self.navigationItem.title = @"大学名录";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"campus_search_tag"] style:UIBarButtonItemStyleDone target:self action:@selector(searchMethod)];
    __weak typeof(self)weakSelf = self;
    self.headerView = [[CampusListTypeHeaderView alloc]initWithCompleteBlock:^(NSInteger index) {
        if (weakSelf.menuIndex == -1) {
            weakSelf.menuIndex = index;
            [weakSelf.menuView showDropDownInView:weakSelf.view];
        }else if (weakSelf.menuIndex != index) {
            weakSelf.menuIndex = index;
            [weakSelf.menuView reloadOptionsData];
        }else{
            [weakSelf.menuView hideDropDown];
            weakSelf.menuIndex = -1;
        }
    }];
    [self.view addSubview:self.headerView];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,self.headerView.cl_height, kScreenW, kScreenH - self.headerView.cl_height - kNavBarHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];

    self.tableView.backgroundColor = [UIColor whiteColor];
    self.pageIndex = 1;

    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf loadDataSource];
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.tableView.mj_footer = footer;
    
    self.menuView = [[LMJDropdownMenu alloc] init];
    self.menuView.anchorPoint = CGPointMake(0, 36);
    self.menuView.optionsListLimitHeight = kScreenH * 0.6;
    self.menuView.dataSource = self;
    self.menuView.delegate = self;
    
    [self.view addSubview:self.menuView];
    

    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.text = @"没有符合条件的大学";
    self.noDataLb.textColor = C153;
    self.noDataLb.font = font(12);
    self.noDataLb.hidden = YES;
    [self.view addSubview:self.noDataLb];
    
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(-100);
    }];

}

- (void)loadDataSource{
    
    [self.task cancel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"pageIndex"] = @(self.pageIndex);
    param[@"pageSize"] = @(10);
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolList];
    if (self.provinceId != nil && self.provinceId.intValue != -1) {
        param[@"area"] = self.provinceId;
    }
    if (self.batchId != nil && self.batchId.intValue != -1) {
        param[@"batch"] = self.batchId;
    }
    if (self.hierarchyId != nil && self.hierarchyId.intValue != -1) {
        param[@"hierarchy"] = self.hierarchyId;
    }
    if (self.typeId != nil && self.typeId.intValue != -1) {
        param[@"type"] = self.typeId;
    }
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolList) parames:param success:^(id responseObj) {
        
        [self hideDataLoadLoadState];
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        if (self.pageIndex == 1) {
            self.dataArray = [CampusSchoolItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[CampusSchoolItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        CGFloat bottom = self.tableView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
                self.tableView.mj_footer.cl_height = 138.0f;
            }
        }else{
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
                self.tableView.mj_footer.cl_height = 44.0f;
            }
        }
        self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        self.noDataLb.hidden = self.dataArray.count > 0;
        
        [self.tableView reloadData];
        
        if (self.pageIndex == 1 && self.dataArray.count != 0) {
            [self.tableView scrollToRow:0 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    } failure:^(NSError *error) {
        [WHToast showErrorWithMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        [self hideDataLoadLoadState];
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}


- (void)searchMethod{
    CampusListSearchViewController *searchVC = [[CampusListSearchViewController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (NSArray *)dropdownMenuListSource{
    return [self updateListItemStatus];
}

- (NSArray *)updateListItemStatus{
    
    CampusConfigModel *model = nil;
    if (self.menuIndex == -1 || self.menuIndex == 0) {
        NSString *title = self.titleArray.firstObject;
        model = [CampusConfigModel getWithKey:title];
    }else{
        NSString *title = self.titleArray[self.menuIndex];
        model = [CampusConfigModel getWithKey:title];
    }
    NSString * idStr = @"";
    if (self.menuIndex == -1 || self.menuIndex == 0) {
        idStr = self.provinceId.stringValue;
    }else if (self.menuIndex == 1){
        idStr = self.typeId.stringValue;
    }else if (self.menuIndex == 2){
        idStr = self.hierarchyId.stringValue;
    }else if (self.menuIndex == 3){
        idStr = self.batchId.stringValue;
    }
    [model.paramList enumerateObjectsUsingBlock:^(CampusParamItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.isSelected = NO;
        if ((idStr.length == 0 && idx == 0) || [obj.name isEqualToString:idStr]) {
            obj.isSelected = YES;
        }
    }];
    return model.paramList;
}

- (NSUInteger)numberOfOptionsInDropdownMenu:(LMJDropdownMenu *)menu{
    return [self updateListItemStatus].count;
}
- (CGFloat)dropdownMenu:(LMJDropdownMenu *)menu heightForOptionAtIndex:(NSUInteger)index{
    return 40.0f;
}
- (NSString *)dropdownMenu:(LMJDropdownMenu *)menu titleForOptionAtIndex:(NSUInteger)index{
    CampusParamItemModel *itemModel =  [self updateListItemStatus][index];
    return itemModel.value;
}
- (CampusParamItemModel *)dropdownMenu:(LMJDropdownMenu *)menu itemModelForOptionAtIndex:(NSUInteger)index{
    CampusParamItemModel *itemModel =  [self updateListItemStatus][index];
    return itemModel;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CampusListItemCell *cell = [CampusListItemCell cellWithTableView:tableView];
    
    CampusSchoolItemModel *itemModel = self.dataArray[indexPath.item];
    itemModel.showLine = self.dataArray.count-1 != indexPath.item;
    [cell setItemModel:itemModel];
    cell.delegate = self;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (void)showCampusDetailWithItemModel:(CampusSchoolItemModel *)itemModel{
    [MobClick event:@"show_school_detail"];
    CampusDetailViewController *dtlVC = [[CampusDetailViewController alloc]init];
    dtlVC.schId = itemModel.id;
    [self.navigationController pushViewController: dtlVC animated:YES];
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)dropdownMenu:(LMJDropdownMenu *)menu didSelectOptionAtIndex:(NSUInteger)index itemModel:(CampusParamItemModel *)itemModel{
    switch (self.menuIndex) {
        case 0:
            self.provinceId = itemModel.isSelected?@(itemModel.name.intValue):nil;
            break;
        case 1:
            self.typeId = itemModel.isSelected?@(itemModel.name.intValue):nil;
            break;
        case 2:
            self.hierarchyId = itemModel.isSelected?@(itemModel.name.intValue):nil;
            break;
        case 3:
            self.batchId = itemModel.isSelected?@(itemModel.name.intValue):nil;
            break;
        default:
            break;
    }
    
    self.headerModel.stauts = itemModel.isSelected;
    self.headerModel.name = itemModel.value;
    self.headerModel.currentIndex = self.menuIndex;
    [self.headerView updateModel:self.headerModel];
    
    
    
    self.menuIndex = -1;
    
    [self showDataLoadState];
    
    self.pageIndex = 1;
    
    [self.tableView.mj_footer resetNoMoreData];
    
    [self loadDataSource];
}

- (void)dropdownMenuDidHidden:(LMJDropdownMenu *)menu{
    
    if (self.menuIndex == -1) {
        return;
    }
    
    [self.headerView resetView];
    self.menuIndex = -1;
}

@end
